package com.example.practicespring.controller.TaskManage;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.practicespring.domain.Server;
import com.example.practicespring.domain.ServerTask;
import com.example.practicespring.service.ServerService;
import com.example.practicespring.service.ServerTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.example.practicespring.ConstantConfig.ConstantConfig.getTimeList;
import static com.example.practicespring.utils.SortTimeUtils.sortTimes;

@Slf4j
@RestController
@RequestMapping(value = "taskManage")
public class TaskManage {

    @Resource
    private ServerTaskService serverTaskService;

    @Resource
    private ServerService serverService;

    private static final List<String> timeAll = getTimeList();

    @SaCheckRole(value = {"admin", "user", "tour"}, mode = SaMode.OR)
    @RequestMapping(value = "taskAbout", method = RequestMethod.POST)
    public SaResult taskTime(@RequestBody ServerTask serverTask) {
        QueryWrapper<ServerTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sid", serverTask.getSid());
        queryWrapper.orderByAsc("task_time");
        List<ServerTask> serverTasks = serverTaskService.list(queryWrapper);

        for (ServerTask server : serverTasks) {
            server.setTimeList(Arrays.stream(server.getTaskTime().split(","))
                    .map(String::trim)
                    .collect(Collectors.toList()));
        }

        return SaResult.data(serverTasks);
    }

    @SaCheckRole(value = {"admin", "user", "tour"}, mode = SaMode.OR)
    @RequestMapping(value = "taskAvailable/{sid}", method = RequestMethod.GET)
    public SaResult taskAvailable(@PathVariable String sid) {
        QueryWrapper<ServerTask> existQuery = new QueryWrapper<>();
        existQuery.eq("sid", sid);
        List<ServerTask> serverData = serverTaskService.list(existQuery);

        List<String> timeExist = new ArrayList<>();
        for (ServerTask server : serverData) {
            String[] timeParts = server.getTaskTime().split(",");
            timeExist.addAll(Arrays.asList(timeParts));
        }


        List<String> difference = timeAll.stream()
                .filter(item -> !timeExist.contains(item)) // 找出差值
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.toList());

        // 转换后的列表，每个元素都是一个Map，包含label和value
        List<Map<String, String>> timeItems = new ArrayList<>();
        // 遍历时间字符串列表，将每个字符串转换为Map并添加到timeItems中
        for (String timeString : difference) {
            Map<String, String> item = new HashMap<>();
            item.put("label", timeString);
            item.put("value", timeString);
            timeItems.add(item);
        }
        return SaResult.data(timeItems);
    }

    @SaCheckRole(value = {"admin", "user"}, mode = SaMode.OR)
    @RequestMapping(value = "subTask", method = RequestMethod.POST)
    public SaResult subTask(@RequestBody ServerTask serverTask) {
        if (serverTask == null) {
            return SaResult.error("信息不存在");
        }
        // 任务名称重复检查
        QueryWrapper<ServerTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_name", serverTask.getTaskName());
        List<ServerTask> taskList = serverTaskService.list(queryWrapper);
        if (!taskList.isEmpty()) {
            return SaResult.error("任务名称重复！");
        }

//        对时间进行排序
        List<String> newTime = sortTimes(serverTask.getTimeList());
        log.info(newTime.toString());

        serverTask.setTaskTime(String.join(",", newTime));
        serverTaskService.save(serverTask);
        return SaResult.ok("添加成功！");
    }

    @SaCheckRole(value = {"admin", "user", "tour"}, mode = SaMode.OR)
    @RequestMapping(value = "taskInfo", method = RequestMethod.GET)
    public SaResult taskInfo() {
        QueryWrapper<ServerTask> allTask = new QueryWrapper<>();
        allTask.orderByAsc("servername");
        List<ServerTask> taskInfo = serverTaskService.list(allTask);

        for (ServerTask server : taskInfo) {
            server.setTimeList(Arrays.stream(server.getTaskTime().split(","))
                    .map(String::trim)
                    .collect(Collectors.toList()));
        }
        return SaResult.data(taskInfo).setMsg("任务信息获取成功！");

    }

    @SaCheckRole(value = {"admin", "user"}, mode = SaMode.OR)
    @RequestMapping(value = "delTask", method = RequestMethod.POST)
    public SaResult delTask(@RequestBody ServerTask serverTask) {
        if (serverTask == null) {
            return SaResult.error("信息不存在");
        }

        if (serverTaskService.removeById(serverTask.getId())) {
            return SaResult.ok("任务删除成功！");
        }
        return SaResult.error("任务删除失败！");

    }

    @SaCheckRole(value = {"admin", "user", "tour"}, mode = SaMode.OR)
    @RequestMapping(value = "searchTask", method = RequestMethod.GET)
    public SaResult searchTask(@RequestParam("taskName") String taskName) {

        QueryWrapper<ServerTask> searchQuery = new QueryWrapper<>();
        searchQuery.like("task_name", taskName);
        List<ServerTask> searchData = serverTaskService.list(searchQuery);

        for (ServerTask server : searchData) {
            server.setTimeList(Arrays.stream(server.getTaskTime().split(","))
                    .map(String::trim)
                    .collect(Collectors.toList()));
        }
        return SaResult.data(searchData).setMsg("任务查询成功！");
    }

    @SaCheckRole(value = {"admin", "user", "tour"}, mode = SaMode.OR)
    @RequestMapping(value = "taskDetail", method = RequestMethod.GET)
    public SaResult taskDetail(@RequestParam("id") Long id) {
        QueryWrapper<ServerTask> oneQuery = new QueryWrapper<>();
        oneQuery.eq("id", id);
        ServerTask oneData = serverTaskService.getOne(oneQuery);

        // 链式设置数据
        // ServerTask build = ServerTask.builder()
        //         .servername("11")
        //         .taskTime("11")
        //         .build();
        //
        // 已选择时段
        oneData.setTimeList(Arrays.stream(oneData.getTaskTime().split(","))
                .map(String::trim)
                .collect(Collectors.toList()));

        // 可选择时段：除其本身任务以外其他任务占用的时段
        QueryWrapper<ServerTask> otherQuery = new QueryWrapper<>();
        otherQuery.eq("sid", oneData.getSid());
        otherQuery.ne("id", id);
        List<ServerTask> otherData = serverTaskService.list(otherQuery);

        // 已有的时间段
        List<String> timeExist = new ArrayList<>();
        for (ServerTask server : otherData) {
            String[] timeParts = server.getTaskTime().split(",");
            timeExist.addAll(Arrays.asList(timeParts));
        }

        // 筛选出可选时间段
        List<String> availableTime = timeAll.stream()
                .filter(item -> !timeExist.contains(item)) // 找出差值
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.toList());

        // 更新options字段内容
        List<Map<String, String>> timeItems = new ArrayList<>();
        // 遍历时间字符串列表，将每个字符串转换为Map并添加到timeItems中
        for (String timeString : availableTime) {
            Map<String, String> item = new HashMap<>();
            item.put("label", timeString);
            item.put("value", timeString);
            timeItems.add(item);
        }
        oneData.setOptions(timeItems);
        return SaResult.data(oneData);
    }

    @SaCheckRole(value = {"admin", "user"}, mode = SaMode.OR)
    @RequestMapping(value = "/subEditTask", method = RequestMethod.POST)
    public SaResult subEditTask(@RequestBody ServerTask serverTask) {
        if (serverTask == null) {
            return SaResult.error("信息不存在");
        }

        serverTask.setTaskTime(String.join(",", serverTask.getTimeList()));

        // 检查是否有任务重命
        QueryWrapper<ServerTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_name", serverTask.getTaskName());
        queryWrapper.ne("id", serverTask.getId());
        List<ServerTask> taskList = serverTaskService.list(queryWrapper);
        if (!taskList.isEmpty()) {
            return SaResult.error("任务名称重复！");
        }

        // 检查时间段是否已经占用
        for (String time : serverTask.getTimeList()) {
            QueryWrapper<ServerTask> queryTime = new QueryWrapper<>();
            queryTime.like("task_time", time);
            List<ServerTask> timeList = serverTaskService.list(queryWrapper);
            if (timeList.size() > 1) {
                return SaResult.error("任务时间段重复: " + time);
            }
        }

        if (serverTaskService.updateById(serverTask)) {
            return SaResult.data(serverTask).setMsg("任务更新成功！");
        }
        return SaResult.error("任务更新失败！");
    }

    @SaCheckRole(value = {"admin", "user", "tour"}, mode = SaMode.OR)
    @RequestMapping(value = "/serverAvailable", method = RequestMethod.GET)
    public SaResult serverAvailable() {
        QueryWrapper<Server> queryWrapper = new QueryWrapper<>();
        List<Server> servers = serverService.list(queryWrapper);

        ArrayList<Map<String, String>> serverItems = new ArrayList<>();
        for (Server server : servers) {
            Map<String, String> item = new HashMap<>();
            item.put("label", server.getName());
            item.put("value", server.getId().toString());
            serverItems.add(item);
        }
        return SaResult.data(serverItems);
    }

    @SaCheckRole(value = {"admin", "user", "tour"}, mode = SaMode.OR)
    @RequestMapping(value = "/serverTime", method = RequestMethod.GET)
    public SaResult serverTime(@RequestParam("id") Integer id) {
        QueryWrapper<ServerTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sid", id);
        List<ServerTask> serverTasks = serverTaskService.list(queryWrapper);

        // 已有时间段
        List<String> timeExist = new ArrayList<>();
        for (ServerTask server : serverTasks) {
            String[] timeParts = server.getTaskTime().split(",");
            timeExist.addAll(Arrays.asList(timeParts));
        }
        // 筛选出可选时间段
        List<String> availableTime = timeAll.stream()
                .filter(item -> !timeExist.contains(item)) // 找出差值
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.toList());

        if (availableTime.isEmpty()) {
            return SaResult.error("没有可选时间段");
        }

        ArrayList<Map<String, String>> serverItems = new ArrayList<>();
        for (String tm : availableTime) {
            Map<String, String> item = new HashMap<>();
            item.put("label", tm);
            item.put("value", tm);
            serverItems.add(item);
        }
        return SaResult.data(serverItems);
    }
}
